import React, { ChangeEvent, useEffect, useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { Input, Space, Button, message } from 'antd'
import initLoginBg from '@/utils/init'
import storage from '@/utils/storage'
import styles from './index.module.scss'

const Login: React.FC = () => {
  const navigate = useNavigate()
  // 加载完这个组件之后，加载背景
  useEffect(() => {
    initLoginBg()
    window.onresize = function () {
      initLoginBg()
    }
  }, [])
  const [userName, setUserName] = useState('admin')
  const [password, setPassword] = useState('123456')
  const changeUserName = (e: ChangeEvent<HTMLInputElement>) => {
    setUserName(e.target.value)
  }
  const changePassword = (e: ChangeEvent<HTMLInputElement>) => {
    setPassword(e.target.value)
  }
  const login = () => {
    if (userName === 'admin' && password === '123456') {
      message.success('登录成功！')
      storage.setStorage('back-token', '123456')
      storage.setStorage('selected_key', '/home')
      navigate('/home', { replace: true })
    }
  }
  return (
    <div className={styles.loginPage}>
      <canvas
        id='canvas'
        style={{ display: 'block' }}></canvas>
      <div className={styles.loginBox}>
        {/* 标题部分 */}
        <div className={styles.title}>
          <h1>小米商城&nbsp;·&nbsp;后台管理系统</h1>
          <p>Strive Everyday</p>
        </div>
        <Space
          direction='vertical'
          size='middle'
          style={{ display: 'flex' }}>
          <Input
            value={userName}
            placeholder='用户名'
            onChange={changeUserName}
          />
          <Input.Password
            value={password}
            placeholder='密码'
            onChange={changePassword}
          />
          <Button
            type='primary'
            block
            onClick={login}>
            登录
          </Button>
        </Space>
      </div>
    </div>
  )
}

export default Login
